/*
 * Copyright The OpenTelemetry Authors
 * SPDX-License-Identifier: Apache-2.0
 */

package com.xiashitech.agent.instrumentation.dubbo.inst.gt27;


import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation;
import io.opentelemetry.javaagent.extension.instrumentation.TypeTransformer;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;

import static net.bytebuddy.matcher.ElementMatchers.*;

public class DubboGt27Instrumentation implements TypeInstrumentation {
    // private static final Logger logger = Logger.getLogger("AbstractChannelHandlerContextInstrumentation");

    @Override
    public ElementMatcher<TypeDescription> typeMatcher() {
        // return implementsInterface(named("com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.channel.ChannelOutboundInvoker"));
        return named("org.apache.dubbo.remoting.exchange.support.header.HeaderExchangeHandler");
    }


    @Override
    public void transform(TypeTransformer transformer) {
        transformer.applyAdviceToMethod(
                isMethod()
                        .and(named("received"))
                        .and(takesArgument(0, named("org.apache.dubbo.remoting.Channel")))
                        .and(takesArgument(1, named("java.lang.Object")))
                        .and(takesArguments(2))
                        .and(isPublic()),
                DubboGt27Instrumentation.class.getName() + "$ReceivedAdvice");
    }

    @SuppressWarnings("unused")
    public static class ReceivedAdvice {

        @Advice.OnMethodEnter
        public static void onEnter(
                @Advice.Argument(value = 1, readOnly = false) Object msg
        ) throws Exception {
            msg =  DubboGt27Handler.handle(msg);
        }

        @Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class)
        public static void onExit() {
            System.out.println("###mmm5");
        }
    }


}

